package com.kaesar.leetcode.LeetCode_051_100;

public class LeetCode_059 {
    public static int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        boolean[][] flag = new boolean[n][n];
        int i = 0, j = -1, count = 0;
        while (count < n * n) {
            // 向右
            while (j + 1 < n && !flag[i][j + 1] && count < n * n) {
                j = j + 1;
                count++;
                result[i][j] = count;
                flag[i][j] = true;
            }

            // 向下
            while (i + 1 < n && !flag[i + 1][j] && count < n * n) {
                i = i + 1;
                count++;
                result[i][j] = count;
                flag[i][j] = true;
            }

            // 向左
            while (j - 1 >= 0 && !flag[i][j - 1] && count < n * n) {
                j = j - 1;
                count++;
                result[i][j] = count;
                flag[i][j] = true;
            }

            // 向上
            while (i - 1 >= 0 && !flag[i - 1][j] && count < n * n) {
                i = i - 1;
                count++;
                result[i][j] = count;
                flag[i][j] = true;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        for (int[] ints : generateMatrix(4)) {
            for (int anInt : ints) {
                System.out.print(anInt + "\t");
            }
            System.out.println();
        }
    }
}
